Repository navigation
fix(ai): use context distinct_id for OpenAI and Gemini embedding events - #1290
pcbeingused333 wants to merge 2 commits into
Conversation
Embedding wrappers only looked at the posthog_distinct_id argument, so a distinct_id set via identify_context() was ignored and the $ai_embedding event was captured personless under the trace id. Resolve the id from the argument first, then the active context, matching the chat/generation path. Signed-off-by: Alex <alex.castillog33@gmail.com>
dustinbyrne
left a comment
There was a problem hiding this comment.
The runtime fix looks solid — we verified OpenAI and Gemini sync/async embedding events (including explicit override, blank-context fallback, and error paths) end-to-end against sdk-mock-server over /i/v1/ai/events, along with local ruff, mypy, check_public_api.py, and the OpenAI/Gemini/utils test suites.
One test coverage concern to address before approval: both new tests check distinct_id and event, but neither asserts that options is absent (so personless=resolved_distinct_id is None is currently unguarded), and _resolve_distinct_id precedence / whitespace-context cases aren't covered yet. Left details inline along with two optional suggestions.
AI-assisted review.
|
|
||
| call_args = mock_client.capture_ai.call_args[1] | ||
| assert call_args["distinct_id"] == "context-user" | ||
| assert call_args["event"] == "$ai_embedding" |
There was a problem hiding this comment.
Concern: Neither new test asserts that options is absent when the embedding event resolves distinct_id from identify_context(), leaving the personless=resolved_distinct_id is None half of the production change in posthog/ai/openai/_embeddings.py (line 66) and posthog/ai/gemini/_shared.py (line 285) unguarded, along with _resolve_distinct_id's precedence and blank-context branches.
Evidence and impact:
- Inside
with new_context(): identify_context("context-user"), this PR changes two user-visible behaviors:distinct_idswitches fromtrace_idto"context-user", andpersonlessswitches fromTrue(options={"process_person_profile": False}) toFalse(optionsomitted). - Both
test_embeddings_use_context_distinct_id(posthog/test/ai/openai/test_openai.py:480-482) andtest_embed_content_uses_context_distinct_id(posthog/test/ai/gemini/test_gemini.py:1388-1390) assert onlycall_args["distinct_id"]andcall_args["event"]. Revertingpersonless=resolved_distinct_id is Noneback topersonless=_user_distinct_id(distinct_id) is Nonein both production files would silently emit personless$ai_embeddingevents (options={"process_person_profile": False}) for identified users while all 404 OpenAI and Gemini tests still pass. - Sibling context tests in this repo (
test_streaming_uses_outer_context_distinct_idfrom fix(ai): use the context distinct id for streamed generations #1286 andtest_outer_context_distinct_id_is_usedinposthog/test/ai/anthropic/test_anthropic.py) assertassert "options" not in call_argsto guard this contract (capture-aispec: only fallback trace IDs forceoptions.process_person_profile: false).
Recommendation:
Consider adding assert "options" not in call_args to both test_embeddings_use_context_distinct_id (here) and test_embed_content_uses_context_distinct_id (posthog/test/ai/gemini/test_gemini.py:1390), plus a focused test covering explicit posthog_distinct_id overriding identify_context and a whitespace-only context falling back to a personless trace_id.
Test sketch (not executed as a committed test; equivalent scenarios passed on head f3c8d48b via local mock-server smoke testing):
# In both test_embeddings_use_context_distinct_id and test_embed_content_uses_context_distinct_id:
assert call_args["distinct_id"] == "context-user"
assert call_args["event"] == "$ai_embedding"
assert "options" not in call_args
# Plus in posthog/test/ai/test_utils.py (or alongside the embedding tests):
def test_resolve_distinct_id_precedence_and_blank_values():
from posthog import identify_context, new_context
from posthog.ai.utils import _resolve_distinct_id
with new_context(fresh=True):
assert _resolve_distinct_id(None) is None
identify_context(" ")
assert _resolve_distinct_id(None) is None
identify_context("context-user")
assert _resolve_distinct_id(None) == "context-user"
assert _resolve_distinct_id(" ") == "context-user"
assert _resolve_distinct_id("explicit-user") == "explicit-user"|
|
||
| def _resolve_distinct_id(distinct_id: Any) -> Any: | ||
| """The caller's distinct id, else the one from the active PostHog context, else None.""" | ||
| return _user_distinct_id(distinct_id) or _user_distinct_id( |
There was a problem hiding this comment.
Suggestion: _resolve_distinct_id and its callers mix or truthiness with is None, which mishandles falsy non-string distinct IDs such as integer 0.
Evidence and reachability:
_user_distinct_id(0)returns0(notNone) because_explicit_distinct_id(0)usesstringify_id(0) == "0".- In
_resolve_distinct_id(posthog/ai/utils.py:77) and the callers (posthog/ai/openai/_embeddings.py:63-66,posthog/ai/gemini/_shared.py:282-285),resolved_distinct_id or trace_idtreats0as falsy whilepersonless=resolved_distinct_id is Nonetreats0as present. - Executed base (
84fc9e06) vs head (f3c8d48b) comparison:with new_context(): identify_context(0); client.embeddings.create(..., posthog_trace_id="t4"):- Base:
distinct_id="t4",options={"process_person_profile": False} - Head:
distinct_id="t4",options=None(emits a random trace UUID withoutprocess_person_profile: False)
- Base:
with new_context(): identify_context("context-user"); client.embeddings.create(..., posthog_distinct_id=0, posthog_trace_id="t5"):- Base:
distinct_id="t5",options=None - Head:
distinct_id="context-user",options=None(explicit0is overridden by the context user)
- Base:
- Reachability is low because
identify_context(distinct_id: str)andposthog_distinct_id: Optional[str]are typedstr, so only untyped/dynamic callers passing integer0hit this.
Recommendation:
Consider using explicit is not None checks so truthiness and personless cannot disagree:
def _resolve_distinct_id(distinct_id: Any) -> Any:
"""The caller's distinct id, else the one from the active PostHog context, else None."""
resolved = _user_distinct_id(distinct_id)
if resolved is not None:
return resolved
return _user_distinct_id(contexts.get_context_distinct_id())and in posthog/ai/openai/_embeddings.py:63 / posthog/ai/gemini/_shared.py:282:
distinct_id=resolved_distinct_id if resolved_distinct_id is not None else trace_id,| return distinct_id if _explicit_distinct_id(distinct_id) is not None else None | ||
|
|
||
|
|
||
| def _resolve_distinct_id(distinct_id: Any) -> Any: |
There was a problem hiding this comment.
Suggestion: Now that #1286 (470a6413) has landed on main with the identical _user_distinct_id(...) or _user_distinct_id(contexts.get_context_distinct_id()) expression in capture_streaming_event (posthog/ai/utils.py:1321-1323 on main), consider reusing _resolve_distinct_id(event_data.get("distinct_id")) there if you rebase onto main, so both streaming and embedding paths share one helper. (No merge conflict exists either way.)
…checks Address review: assert options are absent for context-resolved embedding events, add _resolve_distinct_id precedence/blank tests, and compare resolved ids with 'is not None' so a falsy id such as 0 cannot disagree between distinct_id and personless. Signed-off-by: Alex <alex.castillog33@gmail.com>
|
Thanks for the thorough review. Pushed 01feddc:
I left the This reply was drafted with an AI coding assistant (Claude); the change was tested with the OpenAI/Gemini/utils suites. |
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for following up — the "options" not in call_args assertions, _resolve_distinct_id precedence/blank/falsy-0 tests, and is not None checks address the earlier feedback cleanly, and deferring the capture_streaming_event cleanup keeps this well-scoped. Verified locally with ruff, mypy, check_public_api.py, the AI unit tests, and both synthetic and live OpenAI (text-embedding-3-small) + Gemini (gemini-embedding-001) embedding calls captured by sdk-mock-server over /i/v1/ai/events. LGTM!
AI-assisted review.
Related to #1284 (same bug in the embedding path; #1284 itself covers streaming and is addressed by #1286)
💡 Motivation and Context
The OpenAI (
_embeddings.py) and Gemini (gemini/_shared.py) embedding wrappers built$ai_embeddingevents from theposthog_distinct_idargument only. A distinct ID set withidentify_context()was ignored, so the event was captured personless under the trace ID. The chat/generation path already readsget_context_distinct_id().Both wrappers now resolve the ID through a small
_resolve_distinct_idhelper inposthog/ai/utils.py: the explicit argument first, then the active context's ID, then the existing trace-ID fallback (still personless).💚 How did you test it?
embeddings.create, Geminiembed_content) that call the wrapper insidenew_context()afteridentify_context("context-user")and assert the captureddistinct_id. Both fail on main (the trace ID is used) and pass with the fix.posthog/test/ai/openaiandposthog/test/ai/gemini: 404 passed, 6 skipped.ruff format --checkis clean.📝 Checklist
If releasing new changes
sampo addto generate a changeset file (added.sampo/changesets/embeddings-context-distinct-id.mdin the same format)🤖 Agent context
Autonomy: Fully autonomous
_shared.py, so it is covered by the same change; the streaming-event path (capture_streaming_event) is left to fix(ai): use the context distinct id for streamed generations #1286.